package com.example.time;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    private Handler mHandler;
    private static final int MSG_UPDATE_CURRENT_TIME = 1;
    private TextView tv_time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_time = (TextView) this.findViewById(R.id.id_time);//tv_time与文本框绑定
        mHandler = new MyHandler(this);
        mHandler.sendEmptyMessageDelayed(MSG_UPDATE_CURRENT_TIME, 500);
    }

    private static class MyHandler extends Handler {
        private WeakReference<MainActivity> mActivity;

        public MyHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();
            switch (msg.what) {
                case MSG_UPDATE_CURRENT_TIME:
                    activity.updateCurrentTime();
                    sendEmptyMessageDelayed(MSG_UPDATE_CURRENT_TIME, 10);//设置文本框内时间的更新速度，现在为10毫秒更新一次
                    break;
                default:
                    break;
            }
        }
    }

    private void updateCurrentTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("  hh:mm:ss:SS");//设置输出格式，当前格式为“时：分：秒：毫秒（前两位）”
        Date curDate = new Date(System.currentTimeMillis());
        String time = simpleDateFormat.format(curDate);
        tv_time.setText(time);
    }
}